/**
 * 
 */
package com.ims.common.aspect;

import java.io.Serializable;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;

import com.ims.stocks.model.UserDetails;
import com.opensymphony.xwork2.ActionContext;

/**
 * @author Achal B.I
 * 
 */
public class AroundAdvice implements MethodInterceptor {

	/**
	 * 
	 */

	private static Logger LOG = Logger.getLogger(AroundAdvice.class);

	public AroundAdvice() {
		super();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * display method statistics.
	 * 
	 * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept .MethodInvocation)
	 */
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		Serializable entry = "";
		String pageName = "";
		try {
			UserDetails uinfo = null;
			try {
				uinfo = (UserDetails) ActionContext.getContext().getSession().get("userInfo");
				pageName = ActionContext.getContext().getName();
				entry = uinfo.getEmployee();
			} catch (Exception e) {
				// do nothing..
				// only null pointer exceptions are expected here.
				// when the userInfo object is null.
				LOG.info("Operation Not Supported for page "+pageName +" User is not logged in.");
				entry = "";
			}
			LOG.info(String.format("Emp SlNo: %s Page: %s / Method called \t : %s(%s)",entry,  pageName, invocation.getThis().getClass().getSimpleName()
					+ "." + invocation.getMethod().getName()));
		} catch (Exception e) {
			// lazy initialization Exception caused on some occasions.
			LOG.info(String.format("Emp SlNo: %s Page: %s / Method called \t : %s", entry, pageName, invocation.getMethod().getName()));
		}
		Long startTime = System.currentTimeMillis();
		Object res = invocation.proceed();
		Long endTime = (System.currentTimeMillis() - startTime);
		LOG.info(String.format("Emp SlNo: %s Page: %s / Method returned \t : %s %s", entry, pageName, invocation.getThis().getClass().getSimpleName() + "."
				+ invocation.getMethod().getName(), res==null?null:res.getClass().getSimpleName())
				+ " took : " + endTime + "ms.");
		return res;
	}

}
